package com.quan.wx.web.enter.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.quan.base.common.base.web.support.BaseResult;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.base.common.utils.HttpClientUtil;
import com.quan.base.common.utils.IpHelper;
import com.quan.base.common.utils.XmlUtils;
import com.quan.common.wx.utils.pay.UnifiedOrderRequest;
import com.quan.common.wx.utils.pay.UnifiedOrderResponse;
import com.quan.common.wx.utils.pay.WXPayUtil;

//@RestController
//@RequestMapping(value = "/wx/pay")
public class _WeixinPayController extends BaseController {

	//@PostMapping(value = "/toPay")
	public Object toPay() {
		// APPID
		String appid = "wx36ffa95bb80d94dc";
		// 秘钥
		String key = "271d3367783ed5a77c36302ea3c1d3cd";
		// 商户号
		String mch_id = "1367010102";
		// 统一支付接口
		String unifiedorderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";

		// 订单ID
		String orderId = WXPayUtil.generateUUID();
		// 随机字符串
		String noncestr = WXPayUtil.generateNonceStr();

		Map<String, Object> map = new HashMap<>();
		Map<String, String> requestMap = new HashMap<String, String>();
		// 公众账号ID
		requestMap.put("appid", appid);
		// 商户号
		requestMap.put("mch_id", mch_id);
		// 随机字符串
		requestMap.put("nonce_str", noncestr);
		// 商品描述
		requestMap.put("body", "学车招生平台-老司机班报名");
		// 商户订单号
		requestMap.put("out_trade_no", orderId);
		// 标价金额
		requestMap.put("total_fee", "1");
		// 终端IP
		requestMap.put("spbill_create_ip", IpHelper.getIpAddr(request));
		// 通知地址
		requestMap.put("notify_url", "http://yhaoquan.imwork.net/wx/pay/paymentNotice");
		// 交易类型
		requestMap.put("trade_type", "JSAPI");
		// 商品详情
		requestMap.put("detail", "商品详细描述");

		// 支付用户openid
		requestMap.put("userWeixinOpenId", "oIsgAtAPjJ-8GvUXljx_EB7yqbpc");

		// 签名
		try {
			Map<String, Object> orderInfo = WXPayUtil.createOrderInfo(requestMap, key);
			UnifiedOrderRequest unifiedOrderRequest = (UnifiedOrderRequest) orderInfo.get("unifiedOrderRequest");
			String orderInfo_toString = (String) orderInfo.get("orderInfo_toString");

			logger.debug("发起统一下单请求------------------------------------------\r\n{}\r\n", orderInfo_toString);
			
			String orderResponseStr = HttpClientUtil.post(unifiedorderUrl, orderInfo_toString);
			Map<String, String> xmlToMap = WXPayUtil.xmlToMap(orderResponseStr);
			UnifiedOrderResponse orderResponse = JSON.parseObject(JSON.toJSONString(xmlToMap), UnifiedOrderResponse.class);
			
			logger.debug("统一下单请求返回结果------------------------------------------\r\n{}\r\n", XmlUtils.beanToXml(orderResponse,"xml").replace("__", "_"));
			

			if (null != orderResponse && "SUCCESS".equals(orderResponse.getReturn_code()) && "SUCCESS".equals(orderResponse.getResult_code())) {
				String timestamp = String.valueOf(WXPayUtil.getCurrentTimestamp());
				map.put("timestamp", timestamp);
				map.put("noncestr", noncestr);

				SortedMap<String, String> packageParams = new TreeMap<String, String>();
				packageParams.put("appId", appid);
				packageParams.put("signType", "MD5");
				packageParams.put("nonceStr", noncestr);
				packageParams.put("timeStamp", timestamp);
				String packages = "prepay_id=" + orderResponse.getPrepay_id();
				packageParams.put("package", packages);
				String sign = null;// 这个梗，就是开头说的，弄了半天才弄出来的
				try {
					sign = WXPayUtil.generateSignature(packageParams, key);
				} catch (Exception e) {
					map.put("result", -1);
					e.printStackTrace();
				}
				if (sign != null && !"".equals(sign)) {
					map.put("paySign", sign);
					map.put("result", 1);
				} else {
					map.put("result", -1);
				}
				map.put("prepay_id", orderResponse.getPrepay_id());
				map.put("unifiedOrderRequest", unifiedOrderRequest);
				
				logger.debug("返回客户端数据------------------------------------------\r\n{}", map);
				return map;
			} else { // 不成功
				String text = "调用微信支付出错，返回状态码：" + orderResponse.getReturn_code() + "，返回信息：" + orderResponse.getReturn_msg();
				if (orderResponse.getErr_code() != null && !"".equals(orderResponse.getErr_code())) {
					text = text + "，错误码：" + orderResponse.getErr_code() + "，错误描述：" + orderResponse.getErr_code_des();
				}
				logger.error(text);
				map.put("result", -1);
				return map;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return BaseResult.ok();
	}

	/**
	 * 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数
	 * 
	 * @return
	 */
	//@RequestMapping(value = "/paymentNotice")
	public Object paymentNotice(HttpServletRequest request) {
		System.out.println("异步接收微信支付结果通知");

		return BaseResult.ok();
	}

}
